package com.chrudgames.stayintouch;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.telephony.PhoneNumberUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.SimpleCursorAdapter.ViewBinder;



public class Stats extends ListActivity  {

	
	 private static Context context;
	 String DurationPreference = "";


public String phoneNumbers = "";	

public String[] values = { "", "", "", "", "" };



static final String[] arr = { "_id", "date", "number", "type", "duration" };

public MatrixCursor cCursor = new MatrixCursor(arr);

class CCall implements Comparable<CCall> { 
    Long cDate; 
	String cNumber;
    int cType;
    int cDuration;
    CCall( Long d, String s, int i, int ii ) { 
        cDate = d;
    	cNumber = s;
        cType = i;
        cDuration = ii;
    }

    public int compareTo(CCall two ) {

        return two.cDate.compareTo( this.cDate );
   }
   public String toString(){
       return "CCall[cDate="+cDate+", cNumber="+cNumber+"]";
   }
}


public ArrayList<CCall> arrCall = new ArrayList<CCall>();



	  @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.stats);
	    
	       context = getApplicationContext();
	        
	       phoneNumbers = "";
  		 
		   arrCall.clear();
		 	
		   getInfo();
		    getCalls();
		    getSMS();
		    getTotals();
		    linkList();
		    
		    arrCall = null;
	       
	        
	    }

	
	  @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.layout.menu, menu);
	        return true;
	    }
	    
	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        // Handle item selection
	        switch (item.getItemId()) {
	            
	        case R.id.communicate:
	        	Intent i4 = new Intent(this, Communicate.class);

	        	startActivity(i4);
	        	return true;
	      	
	        case R.id.options:
	            	Intent i = new Intent(this, Prefs.class);
	               	startActivity(i);
	    	
	                return true;
	            case R.id.upgrade:
	            	Intent i3 = new Intent(this, Upgrade.class);
	               	startActivity(i3);
	                return true;
	            case R.id.help:
	            	Intent i2 = new Intent(this, Help.class);
	               	startActivity(i2);
	                return true;
	            default:
	                return super.onOptionsItemSelected(item);
	        }
	    }
	  
	   @Override
	    public void onWindowFocusChanged(boolean hasFocus) {
	        
	    	if(hasFocus){
	    		 
	    	}
	    }
	  
	  public void getInfo(){
		  
		  

	        SharedPreferences prefs = PreferenceManager
	                            .getDefaultSharedPreferences(getBaseContext());
	   
	        DurationPreference = prefs.getString("pref_duration", "60");
	        if(DurationPreference.length()<1){DurationPreference="0";}
	    	
	        
	        Bundle b = getIntent().getExtras();
	        String lookupKey = b.getString("lookupKey");
	    	String tmpPhone = "";
	        
	        
	    	Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
	    	
	    	
	    	Cursor c = getContentResolver().query(lookupUri, new String[]{Contacts.DISPLAY_NAME, Contacts.LAST_TIME_CONTACTED, Contacts.HAS_PHONE_NUMBER},null, null, null);
	    	try {
	    	    c.moveToFirst();
	    	    String displayName = c.getString(0);
	    	    if(displayName.length()>26)displayName = c.getString(0).substring(0, 26);
	    	   // Long lastContact = c.getLong(1);
	    	    
	    	    TextView mTextView = (TextView) findViewById(R.id.tvName);
	            mTextView.setText(displayName);
	                         

	            
	            String hasPhone = c.getString(2);
   
            
	           if (hasPhone.contains("1")) { 

	      	
	        	   
	            Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY +" = '" + lookupKey + "'", null, null);  
	      	      while (phones.moveToNext()) { 
	      	    	  

	      	    	tmpPhone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));  
	      	    	tmpPhone = tmpPhone.replaceAll("[^0-9]","");
	      	    	
	      	    	
	      	    	if(tmpPhone.length()>6){tmpPhone = tmpPhone.substring(tmpPhone.length() - 6);}
	      	    	
	      	    	
	      	    	
	      	        phoneNumbers = phoneNumbers + "'" + tmpPhone + "',";

	      	
	      	      
	      	      } 
	      	   phones.close(); 
	      	   
	      	 if(phoneNumbers.length()>1){  phoneNumbers = phoneNumbers.substring(0, phoneNumbers.length() - 1);}
	      	//phoneNumbers = phoneNumbers.replaceAll("[^0-9]","");

	      	}
	            
	            
	    	} finally {
	    	    c.close();
	    	}
	    	  
	    	
	    	
	    }
	    
	    
		  
	    public void linkList(){

	    	
	    	//Collections.sort(arrCall);
	    	
	    	for(int i=0;i<arrCall.size();i++)
	    	{

			       values[0] = String.valueOf(i);
				   values[1] = String.valueOf(arrCall.get(i).cDate);
				   values[2] = String.valueOf(arrCall.get(i).cNumber);
				   values[3] = String.valueOf(arrCall.get(i).cType);
				   values[4] = String.valueOf(arrCall.get(i).cDuration);
				   cCursor.addRow(values);      
	    	}
	    	
	    	
	         
		      String[] fields = new String[]  { android.provider.CallLog.Calls.DATE, android.provider.CallLog.Calls.NUMBER, android.provider.CallLog.Calls.TYPE, android.provider.CallLog.Calls.TYPE, android.provider.CallLog.Calls.TYPE, android.provider.CallLog.Calls.TYPE, android.provider.CallLog.Calls.TYPE, android.provider.CallLog.Calls.DURATION };
		      int[] views = new int[] { R.id.tvDate, R.id.tvNumber, R.id.imgCallOut,  R.id.imgCallIn,  R.id.imgSMSOut,  R.id.imgSMSIn,  R.id.imgCallMissed,  R.id.tvDuration };
		            
		       

            
            SimpleCursorAdapter adapter = new SimpleCursorAdapter(
                   this,
                   R.layout.stats_row_view,
                 cCursor, fields, views);
            
            adapter.setViewBinder(new CallViewBinder());

           setListAdapter(adapter);
   
	       adapter.setViewBinder(new CallViewBinder());
	    	

	    }
	  
	    
	    public void getCalls(){
	    	
	    	
		    
	    	final String[] projection = null;
	    	final String selection = "duration>" + DurationPreference + " and substr(replace(number, '-',''),-6,6) IN (" + phoneNumbers + ")";
	    	final String selectionArgs[] = null;// phoneNumbers;
	    	final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
	    	Cursor c = null;
	    	
	    	
	    	//try{
	    	  
	        
	           c = getContentResolver().query(
	    	            Uri.parse("content://call_log/calls"),
	    	            projection,
	    	            selection,
	    	            selectionArgs,
	    	            sortOrder);
	           
	
	            
		           if (c.moveToFirst()) {
			              
		        	//   datLatest = c.getLong(0);
		        	   
		        	   do {
		                   
		        		  
		       		CCall call = new CCall(c.getLong(c.getColumnIndex("date")),c.getString(c.getColumnIndex("number")),c.getInt(c.getColumnIndex("type")),c.getInt(c.getColumnIndex("duration")));
		        		
		        	arrCall.add(call);
		        		
		        		  // Log.w("SIT", c.getCount() + "");  
		        		 //Log.w("SIT",android.text.format.DateFormat.getTimeFormat(context).format(new Date(c.getLong(c.getColumnIndex("date")))));
		                   
		        		   
		                   
		               } while (c.moveToNext()); 
	            
	    		
	    	}
		         
		           
		  
			                      
		       		        
	    	//}catch(Exception ex){
	    	//	Log.w("SIT",ex.getMessage().toString());
	    	//}finally{
	    	   c.close();
	    	//}
	    	
	    	   
	    }
	    
	    public void getSMS(){
	    	
	    	
		    
	    	final String[] projection = null;
	    	final String selection = "substr(replace(address, '-',''),-6,6) IN (" + phoneNumbers + ")";//  "person='" + lookupKey +"'";
	    	final String selectionArgs[] = null;// phoneNumbers;
	    	final String sortOrder = null;
	    	Cursor c = null;
	    	
	    	
	    	//try{
	    	  
	        
	           c = getContentResolver().query(
	    	            Uri.parse("content://sms/sent"),
	    	            projection,
	    	            selection,
	    	            selectionArgs,
	    	            sortOrder);
	           
	
	            
		           if (c.moveToFirst()) {
			              
		        	//   datLatest = c.getLong(0);
		        	   
		        	   do {
		                   
		        		  
		        		CCall call = new CCall(c.getLong(c.getColumnIndex("date")),c.getString(c.getColumnIndex("address")),4,0);
		        		
		        		arrCall.add(call);
		        		
		        		  // Log.w("SIT", c.getCount() + "");  
		        		 //Log.w("SIT",android.text.format.DateFormat.getTimeFormat(context).format(new Date(c.getLong(c.getColumnIndex("date")))));
		                   
		        		   
		                   
		               } while (c.moveToNext()); 
	            
	    		
	    	}
		         
		           
		           c = getContentResolver().query(
		    	            Uri.parse("content://sms/inbox"),
		    	            projection,
		    	            selection,
		    	            selectionArgs,
		    	            sortOrder);
		           
		
		            
			           if (c.moveToFirst()) {
				              
			        	//   datLatest = c.getLong(0);
			        	   
			        	   do {
			                   
			        		 
			        		   CCall call = new CCall(c.getLong(c.getColumnIndex("date")),c.getString(c.getColumnIndex("address")),5,0);
				        		
				        		arrCall.add(call);
			        		
			                   
			               } while (c.moveToNext()); 
		            
		    		
		    	}
			                      
		       		        
	    	//}catch(Exception ex){
	    	//	Log.w("SIT",ex.getMessage().toString());
	    	//}finally{
	    	   c.close();
	    	//}
	    	
	    	   
	    }
	    
	    private static class CallViewBinder implements ViewBinder {

	    	  
	    	
	        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
	        	

	        	   if(view.getId()== R.id.tvDate) {
	        		  
	        		  ((TextView) view).setText(android.text.format.DateFormat.getMediumDateFormat(context).format(new Date(cursor.getLong(columnIndex))) +
	        		" - " + android.text.format.DateFormat.getTimeFormat(context).format(new Date(cursor.getLong(columnIndex))));
	        		  
	        		  return true;
	        		  
	        	  } else if((view instanceof ImageView)) {
	                
	        		  if(cursor.getInt(columnIndex)==2) {
	        		  
	        			  if(view.getId()==R.id.imgCallOut){
	                		               		 	                		
	                		view.setVisibility(View.VISIBLE);
	                    		
	                	}else{
	                		view.setVisibility(View.INVISIBLE);
	                	}
	        			  
	        		  }else if(cursor.getInt(columnIndex)==1) {
	        		  
	        			  if(view.getId()==R.id.imgCallIn){
	                		               		 	                		
	                		view.setVisibility(View.VISIBLE);
	                    		
	                	}else{
	                		view.setVisibility(View.INVISIBLE);
	                	}
	        			
	        		  }else if(cursor.getInt(columnIndex)==4) {
		        		  
	        			  if(view.getId()==R.id.imgSMSOut){
	                		               		 	                		
	                		view.setVisibility(View.VISIBLE);
	                    		
	                	}else{
	                		view.setVisibility(View.INVISIBLE);
	                	}
	        			  
	        		  }else if(cursor.getInt(columnIndex)==5) {
		        		  
	        			  if(view.getId()==R.id.imgSMSIn){
	                		               		 	                		
	                		view.setVisibility(View.VISIBLE);
	                    		
	                	}else{
	                		view.setVisibility(View.INVISIBLE);
	                	}
	        			  
	        		  }else {
	        		  
	        			  if(view.getId()==R.id.imgCallMissed){
	                		               		 	                		
	                		view.setVisibility(View.VISIBLE);
	                    		
	                	}else{
	                		view.setVisibility(View.INVISIBLE);
	                	}
	        		  } 
	        	  
	        		  return true;
	        	  
	        	  } else if(view.getId()== R.id.tvNumber) {
		            
	        	//	  try {
	        			  ((TextView) view).setText(PhoneNumberUtils.formatNumber(cursor.getString(columnIndex)));
	        	//	  } catch(NullPointerException e) {
	        	//		  ((TextView) view).setText(cursor.getString(columnIndex));
	        		//  }  
	        		
	        		  return true;
	        		  
	        	  } else if(view.getId()== R.id.tvDuration) {
		               
	        		  
	        		  
		        		((TextView) view).setText(splitSecond(cursor.getInt(columnIndex)));
		        		  return true;
		        		        		  
	        		  
	        	  } else {
	                    return false;
	                }
	        	  
	        }
	    }
	    
	    public void onClick(View v) {
	    	
	    	switch (v.getId()) {
	    	
	    	case R.id.tvName:

	    	    	Bundle b = getIntent().getExtras();
	    	        String lookupKey = b.getString("lookupKey");

	    	  
	    	    Intent intent = new Intent(Intent.ACTION_VIEW);
	        	Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
	    	    intent.setData(lookupUri);
	    	    startActivity(intent);

	          	break;
	    	  	
	    	}
	          
	        }
	    
	    public static String splitSecond(int inSeconds)
	    {
	       
	    	String strResult = "";
	    	
	        int hours = (int) inSeconds / 3600;
	        int remainder = (int) inSeconds - hours * 3600;
	        int mins = remainder / 60;
	        remainder = remainder - mins * 60;
	        int secs = remainder;

	        if(hours>0){ strResult = strResult + hours + " hour ";}
	        if(mins>0){ strResult = strResult + mins + " min ";}
	        if(secs>0){ strResult = strResult + secs + " secs";}
	        
	        return strResult;
	    }

public void getTotals(){
	    	

  	    	
	    //	try{
	
				Collections.sort(arrCall);
	
	    		
	    		int totalTime = 0;
	    		int intIn = 0;
	    		int intOut = 0;
	    		int intMissed = 0;
	    		int intSMSIn = 0;
	    		int intSMSOut = 0;
	    		Long datOldest = null;
	    		Long datLatest = null;
	    		Long interval = null;
	    		Long maxInterval = null;

	            
	           if (arrCall.size() > 0)  {

	        	   datLatest = arrCall.get(0).cDate;
	        	   
	        	   for(int i=0;i<arrCall.size();i++)
	   	    	{

	        	
	        		   if(arrCall.get(i).cType==2) intOut=intOut+1;
	        		   if(arrCall.get(i).cType==1) intIn=intIn+1;
	        		   if(arrCall.get(i).cType==3) intMissed=intMissed+1;
	        		   if(arrCall.get(i).cType==4) intSMSOut=intSMSOut+1;
	        		   if(arrCall.get(i).cType==5) intSMSIn=intSMSIn+1;
	        		   
		        	   totalTime = totalTime + arrCall.get(i).cDuration;
		        		   
		        	  
		        	   if(datOldest!=null){
	        		   
		        		   interval = datOldest - arrCall.get(i).cDate;
		                   
		        		   if(maxInterval==null)maxInterval = interval;
		        		   if(interval>maxInterval)maxInterval = interval;
	                   
	        		   }
	                   
		        		   datOldest = arrCall.get(i).cDate;
		        		   
	               };
	        	   

	            TextView mTextView = (TextView) findViewById(R.id.tvInterval);
	            mTextView.setText(this.getString(R.string.Average) + "\u0020" + (TimeUnit.MILLISECONDS.toSeconds((datLatest - datOldest)/(arrCall.size()))/60/60/24 + 1) 
	            		+ "\u0020" + this.getString(R.string.days_Max) + "\u0020" + TimeUnit.MILLISECONDS.toSeconds(maxInterval)/60/60/24 + "\u0020" + this.getString(R.string.days));
	            
	            mTextView = (TextView) findViewById(R.id.tvDuration);
	            mTextView.setText(this.getString(R.string.Total) + "\u0020" + totalTime/60 + "\u0020" + this.getString(R.string.minutes_Average) + "\u0020" + totalTime/(intOut+intIn)/60 + "\u0020" + this.getString(R.string.minutes));
	            
	            mTextView = (TextView) findViewById(R.id.tvType);
	            mTextView.setText(this.getString(R.string.Outgoing) + "\u0020" + (intSMSOut+intOut)*100/arrCall.size() + "%," + "\u0020" + this.getString(R.string.Incoming) + "\u0020"
	            + (intSMSIn + intIn)*100/arrCall.size() + "%,");
	            
	            mTextView = (TextView) findViewById(R.id.tvCalls);
	            mTextView.setText(this.getString(R.string.Found) + "\u0020" + (intOut+intIn+intMissed) + "\u0020"+ this.getString(R.string.calls_over) + "\u0020"+ DurationPreference.toString() + "\u0020"
	            + this.getString(R.string.seconds) + ", " + (intSMSIn+intSMSOut) + " SMS");
	           
	           }else{
	        	   
	        	   
	        	   TextView mTextView = (TextView) findViewById(R.id.tvInterval);
		            mTextView.setText(this.getString(R.string.No_calls_yet));
		            
		            mTextView = (TextView) findViewById(R.id.tvDuration);
		            mTextView.setText(this.getString(R.string.No_calls_yet));
		            		            
		            mTextView = (TextView) findViewById(R.id.tvType);
		            mTextView.setText(this.getString(R.string.No_calls_yet));
		            
		            mTextView = (TextView) findViewById(R.id.tvCalls);
		            mTextView.setText(this.getString(R.string.Found_no_calls_over) + DurationPreference.toString() + this.getString(R.string.seconds));
	        	   
	        	   
	           }
	            

	  		       		        
	    	//}catch(Exception ex){

	    //	}finally{
	    	  // c.close();
	    //	}
	    	
	    	
	    }
	    
}
